<?php

namespace app\api\controller;

use app\admin\model\Wximportlog;
use app\admin\model\Wxorderinfo;
use app\admin\model\Wxpro;
use app\admin\model\Wxproduct;
use app\common\controller\Api;
use fast\Http;
use think\Cache;
use think\Db;
use think\exception\DbException;

/**
 * 网销订单
 */
class WxOrder extends Api
{

    protected $noNeedLogin = '*';
    protected $layout = '';
    protected $error = null;
    protected $token = '';

    public function _initialize()
    {
        parent::_initialize();
        if (!Cache::get('WxOrderToken')) {
            try {
                $this->login();
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
        }
        $this->token = Cache::get('WxOrderToken');
    }

    /**
     * 获取token
     * @throws \Exception
     */
    protected function login()
    {
        $response = Http::post(
            "https://shoptest.fc62.com/api/login",
            [
                'account' => 17607118143,
                'password' => 'yangliuqq'
            ],
            [
                CURLOPT_HTTPHEADER =>
                    ['Content-type: application/x-www-form-urlencoded']
            ]
        );
        $data = json_decode($response, true);
        if ($data['status'] != 200) {
            $this->error($data['msg']);
        }
        //给token设置过期时间
        Cache::set('WxOrderToken', $data['data']['token'], new \DateTime($data['data']['expires_time']));
    }

    public function getOrder($start,$stop,$username)
    {
        $createtime  = date('Y-m-d H:i:s',time());
        $response = Http::get(
            'https://shoptest.fc62.com/api/admin/order/all_list',
            [
                'start' => $start,
                'stop' => $stop
            ],
            [
                CURLOPT_HTTPHEADER => [
                    "authori-zation: Bearer {$this->token}"
                ]
            ]
        );
        $data = json_decode($response, true);

        if ($data['status'] != 200) $this->error($data['msg']);
        if (!$data['data']) $this->error('没有数据.');
        list($order, $orderInfo) = $this->AddOrder($data['data']);
        $orderinfoData = $this->AddOrderInfo($orderInfo);
        $num = $this->installOrder($order, $orderinfoData);
        $endtime  = date('Y-m-d H:i:s',time());
        if($num > 0) \app\admin\model\Wxorder::msg(['moban'=>'dddr','id'=>$this->getLogId(),'agent_name'=>'网购提分超市','createtime'=>$endtime]);
        $msg = $num ? "一共新增了{$num}条数据." : "没有新的数据需要更新.";
        $this->success($msg);
    }

    protected function installOrder(array $order, $orderinfoData)
    {
        $agent_id = $this->getLogId();
        $num = [];
        Db::startTrans();
        try {
            $wxorder = new \app\admin\model\Wxorder();
            foreach ($order as $or)
            {
                $num[] = $wxorder->insertGetId($or);
            }
            $wxorderinfo = new Wxorderinfo();
            $wxorderinfo->insertAll($orderinfoData);
            $Log = new Wximportlog();
            $row = $Log->get($agent_id);
            $row->order_ids .= implode(',',$num).',';
            $row->save();
            // 提交事务
            Db::commit();

        } catch (DbException $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        unset($order, $orderinfoData);
        return count($num);
    }

    protected function AddOrder(array $array = [])
    {
        $order = [];
        $orderInfo = [];
        foreach ($array as $item) {
            if (!$row = \app\admin\model\Wxorder::get(['order_sn' => $item['order_sn']])) {
                foreach ($item['goodsinfo'] as $info) {
                    $orderInfo[] = $info;
                }
                unset($item['goodsinfo']);
                $item['agent_id'] = 81;
                $item['xdtime'] = strtotime($item['xdtime']);
                $item['createtime'] = time();
                $item['address'] = str_replace(' ','',$item['address']);
                $item['log_id'] = $this->getLogId();
                $order[] = $item;
            }else{
                //订单存在的就更新
                $row->receipt = $item['receipt'];
                $row->amount = $item['amount'];
                $row->phone = $item['phone'];
                $row->address = $item['address'];
                $row->akg = $item['akg'];
                $row->save();
            }

        }
        return [$order, $orderInfo];
    }

    protected function AddOrderInfo(array $array = [])
    {
        $orderInfoData = [];
        foreach ($array as $value) {

            if(strpos($value['goods_name'],'提分宝典') !== false && $value['dk'])
            {
               //高考并且还得选课
                if(strpos($value['goods_name'],'高考全套') !== false && $value['dk'])
                {
                    $value['goods_name'] = str_replace('套装','',$value['goods_name']);
                    $gaokao = '高考';
                    $banben = substr($value['goods_name'],0,stripos($value['goods_name'],'版')+3);
                    $array = array_filter(explode('+',$value['goods_name']));
                    $kemu = array_filter(explode(',',$value['dk']));
                    foreach ($array as $item) {
                        if(strpos($item,'提分宝典') == false)
                        {
                            foreach ($kemu as $ke)
                            {
                                if($banben == '全国版' && $ke == '数学')
                                {
                                    $banben = substr($value['goods_name'],0,stripos($value['goods_name'],'版')+9);
                                }else{
                                    $banben = substr($value['goods_name'],0,stripos($value['goods_name'],'版')+3);
                                }
                                $name = $banben.$item.$gaokao.$ke.'2021';
                                if (!$row = Wxproduct::get(['name' => $name])) {
                                    $this->error('商品名称:'.$name.',请添加商品名称。');
                                }
                                $orderInfoData[] = [
                                    'goods_name' => $row['name'],
                                    'num' => $value['num'],
                                    'order_sn' => $value['order_sn'],
                                    'wxproduct_id' => $row['id'],
                                    'kg' => $row['kg'],
                                    'price' => $row['ministrial'],
                                    'dk' => ''
                                ];
                            }
                        }else{
                            if (!$row = Wxproduct::get(['name' => trim($item.'2021')])) {
                                $this->error('商品名称:'.$item.'2021'.',请添加商品名称。');
                            }
                            $orderInfoData[] = [
                                'goods_name' => $row['name'],
                                'num' => $value['num'],
                                'order_sn' => $value['order_sn'],
                                'wxproduct_id' => $row['id'],
                                'kg' => $row['kg'],
                                'price' => $row['ministrial'],
                                'dk' => ''
                            ];
                        }
                    }
                }
            }else{
                try {
                    if (!$row = Wxproduct::get(['name' => trim($value['goods_name'])])) {
                        $this->error('商品名称:'.$value['goods_name'].',请添加商品名称。');
                    }
                    if($row->type == 3 || $row->type == 18)
                    {
                        if (!$row = Wxproduct::get(['name' => trim($value['goods_name']).'2020'])) {
                            $this->error('商品名称:'.$value['goods_name'].',请添加新版商品名称。');
                        }
                    }

                } catch (DbException $e) {
                    $this->error($e->getMessage());
                }
                $orderInfoData[] = [
                    'goods_name' => $row['name'],
                    'num' => $value['num'],
                    'order_sn' => $value['order_sn'],
                    'wxproduct_id' => $row['id'],
                    'kg' => $row['kg'],
                    'price' => $row['ministrial'],
                    'dk' => $value['dk'] ? $value['dk'] : ''
                ];
            }
        }
        return $orderInfoData;
    }

    protected function getLogId()
    {
        $Log = new Wximportlog();
        $row = $Log->whereTime('createtime', 'd')->where('agent_id',81)->find();
        $id = 0;
        if(!$row)
        {
            $id = $Log->insertGetId([
                'agent_id'=>81,
                'createtime'=>time()
            ]);
        }else{
            $id = $row->id;
        }
        return $id;
    }


    public  function orderSend(array $array)
    {
        $array['info'] = json_encode($array['info'],true);
        $response = Http::post(
            'https://shoptest.fc62.com/api/admin/order/delivery/keep_handle',
            $array,
            [
                CURLOPT_HTTPHEADER => [
                    "authori-zation: Bearer {$this->token}"
                ]
            ]
        );
        $data = json_decode($response, true);
        if($data['status'] != 200)
        {
            \app\admin\model\Wxorder::msg(['moban'=>'error','text'=>$data['msg']]);
        }
    }


}
